package com.lkx.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.blade.kit.json.JSONArray;
import com.blade.kit.json.JSONObject;
import com.lkx.domain.User;
import com.wechat.util.Constant;
import com.wechat.util.Matchers;
import com.wechat.util.MessageListener;
import com.wechat.util.WechatApiUtil;
import com.wechat.util.WechatMeta;
import com.wechat.util.WxLocalCache;

@Controller
public class IndexController {
	
	@RequestMapping("/login")
    public String login() {
        return "login";
    }
	
	@RequestMapping("/test")
	@ResponseBody
	public String test(String key,HttpServletRequest request){
		Map<String,Book> map = DB.getAll();
		Book book =  map.get(key);
		return book.getName()+"-"+book.getAuthor()+request.getSession().getId();
	}
	
	@RequestMapping("/")
	public ModelAndView index(ModelAndView view) {
		view.setViewName("wxindex");
		String uuid = WechatApiUtil.getUUID();
		view.addObject("codeImg", WechatApiUtil.getQrCode(uuid));
		view.addObject("uuid", uuid);
		return view;
	}

	@RequestMapping("/wxlogin")
	@ResponseBody
	public Map<String, String> login(ModelAndView view, String uuid) throws InterruptedException {
		Map<String, String> resultMap = new HashMap();
		while (true) {

			String res = WechatApiUtil.waitLogin(0, uuid);
			String code = Matchers.match("window.code=(\\d+);", res);

			if (!Constant.HTTP_OK.equals(code)) {
				System.out.println("wait for login...");
				Thread.sleep(2000);
				continue;
			}
			WechatMeta meta = WechatApiUtil.newWechatMeta(res);
			WechatApiUtil.login(meta);
			JSONObject wxInitObj = WechatApiUtil.wxInit(meta);
			WechatApiUtil.openStatusNotify(meta);

			JSONArray contactList = wxInitObj.get("ContactList").asArray();
			WxLocalCache.init(meta).setLatestContactList(contactList);

			MessageListener listener = new MessageListener(meta);
			listener.listen();

			break;
		}

		resultMap.put("code", "0");
		resultMap.put("message", "登录成功,已变身为蠢萌蠢萌的机器人...");
		
		JSONArray arry = WxLocalCache.instance().getContactList();
		
		
		return resultMap;
	}
	
	@RequestMapping("/index")
    public ModelAndView login(ModelAndView view) {
		view.setViewName("index");
		view.addObject("username", "李凯旋");
        return view;
    }
	
    @RequestMapping("/loginUser")
    public String loginUser(String username,String password,HttpSession session) {
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);   //完成登录
            User user=(User) subject.getPrincipal();
            session.setAttribute("user", user);
            return "index";
        } catch(Exception e) {
            return "login";//返回登录页面
        }
        
    }
    @RequestMapping("/logOut")
    public String logOut(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
//        session.removeAttribute("user");
        return "login";
    }

}
